/**
 * 结果展示表格组件 - 模仿报关单样式
 */
import React, { useState, useEffect } from 'react';
import { Card, Input, Table, Typography, Space, Tag, Collapse, Tooltip } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, EditOutlined, InfoCircleOutlined } from '@ant-design/icons';
import type { ExtractedFields, ProductItem, FieldGroup } from '../types/customs';
import '../styles/customs-table.css';

const { Title, Text } = Typography;
const { Panel } = Collapse;
const { TextArea } = Input;

interface ResultTableProps {
  data: ExtractedFields;
  onDataChange: (data: ExtractedFields) => void;
  extractionResults?: any[];
  rawContents?: Record<string, string>;  // 新增: 智能体原始content内容
}

// 字段分组配置
const fieldGroups: FieldGroup[] = [
  {
    title: '基本信息',
    fields: [
      { label: '进口日期', key: '进口日期' },
      { label: '申报日期', key: '申报日期' },
      { label: '境内收货人', key: '境内收货人', span: 2 },
      { label: '进境关别', key: '进境关别' },
      { label: '境外发货人', key: '境外发货人', span: 2 },
      { label: '运输方式', key: '运输方式' },
      { label: '运输工具名称及航次号', key: '运输工具名称及航次号' },
      { label: '提运单号', key: '提运单号' },
      { label: '货物存放地点', key: '货物存放地点' },
      { label: '消费使用单位', key: '消费使用单位', span: 2 },
    ],
  },
  {
    title: '监管信息',
    fields: [
      { label: '监管方式', key: '监管方式' },
      { label: '征免性质', key: '征免性质' },
      { label: '启运港', key: '启运港' },
      { label: '贸易国（地区）', key: '贸易国（地区）' },
      { label: '启运国（地区）', key: '启运国（地区）' },
      { label: '经停港', key: '经停港' },
      { label: '入境口岸', key: '入境口岸' },
      { label: '包装种类', key: '包装种类' },
      { label: '成交方式', key: '成交方式' },
      { label: '运费', key: '运费' },
      { label: '保费', key: '保费' },
      { label: '自报自缴', key: '自报自缴' },
    ],
  },
  {
    title: '数量信息',
    fields: [
      { label: '件数', key: '件数' },
      { label: '毛重(千克)', key: '毛重(千克)' },
      { label: '净重(千克)', key: '净重(千克)' },
      { label: '随附单证及编号', key: '随附单证及编号', span: 2 },
      { label: '标记唛码及备注', key: '标记唛码及备注', span: 2 },
    ],
  },
  {
    title: '确认信息',
    fields: [
      { label: '特殊关系确认', key: '特殊关系确认' },
      { label: '价格影响确认', key: '价格影响确认' },
      { label: '支付特许权使用费确认', key: '支付特许权使用费确认' },
      { label: '公式定价确认', key: '公式定价确认' },
    ],
  },
  {
    title: '报关信息',
    fields: [
      { label: '报关人员证号', key: '报关人员证号' },
      { label: '报关人员', key: '报关人员' },
      { label: '报关人员电话', key: '报关人员电话' },
      { label: '申报单位', key: '申报单位', span: 2 },
      { label: '报关专用章', key: '报关专用章' },
      { label: '报单签章', key: '报单签章' },
      { label: '海关批注及签章', key: '海关批注及签章', span: 2 },
    ],
  },
];

const ResultTable: React.FC<ResultTableProps> = ({ data, onDataChange, extractionResults = [], rawContents = {} }) => {
  const [editingKey, setEditingKey] = useState<string>('');
  const [localData, setLocalData] = useState<ExtractedFields>(data);

  useEffect(() => {
    setLocalData(data);
  }, [data]);

  // 判断字段是否提取成功
  const isFieldSuccess = (fieldName: string): boolean => {
    const result = extractionResults.find(r => r.field === fieldName);
    return result?.success || false;
  };

  // 处理字段编辑
  const handleFieldChange = (key: keyof ExtractedFields, value: any) => {
    const newData = { ...localData, [key]: value };
    setLocalData(newData);
    onDataChange(newData);
  };

  // 渲染单个字段
  const renderField = (label: string, key: keyof ExtractedFields, span: number = 1) => {
    const value = localData[key];
    const isEditing = editingKey === key;
    const success = isFieldSuccess(key as string);
    const rawContent = rawContents?.[key as string];  // 获取智能体原始内容

    return (
      <tr key={key}>
        <td className="field-label" style={{ width: '120px' }}>
          {label}
          {success ? (
            <CheckCircleOutlined style={{ color: '#52c41a', marginLeft: 8 }} />
          ) : (
            <CloseCircleOutlined style={{ color: '#ff4d4f', marginLeft: 8 }} />
          )}
          {rawContent && (
            <Tooltip 
              title={<pre style={{ maxHeight: '400px', overflow: 'auto', margin: 0, whiteSpace: 'pre-wrap', fontSize: '12px' }}>{rawContent}</pre>}
              placement="right"
              overlayStyle={{ maxWidth: '600px' }}
            >
              <InfoCircleOutlined style={{ color: '#1890ff', marginLeft: 4, cursor: 'help' }} />
            </Tooltip>
          )}
        </td>
        <td 
          className="field-value" 
          colSpan={span}
          onClick={() => setEditingKey(key)}
          style={{ cursor: 'pointer', position: 'relative' }}
        >
          {isEditing ? (
            <Input
              value={value as string || ''}
              onChange={(e) => handleFieldChange(key, e.target.value)}
              onBlur={() => setEditingKey('')}
              autoFocus
              suffix={<EditOutlined />}
            />
          ) : (
            <span>
              {value as string || <Text type="secondary">未提取</Text>}
              <EditOutlined style={{ marginLeft: 8, color: '#999' }} />
            </span>
          )}
        </td>
      </tr>
    );
  };

  // 渲染字段分组
  const renderFieldGroup = (group: FieldGroup) => {
    return (
      <Card 
        key={group.title}
        title={group.title} 
        size="small" 
        style={{ marginBottom: 16 }}
        className="customs-card"
      >
        <table className="customs-table">
          <tbody>
            {group.fields.map((field) => renderField(field.label, field.key, field.span))}
          </tbody>
        </table>
      </Card>
    );
  };

  // 商品明细表格列定义
  const productColumns = [
    {
      title: '项号',
      dataIndex: '项号',
      key: '项号',
      width: 60,
      editable: true,
    },
    {
      title: '商品编号',
      dataIndex: '商品编号',
      key: '商品编号',
      width: 120,
      editable: true,
    },
    {
      title: '商品名称及规格型号',
      dataIndex: '商品名称及规格型号',
      key: '商品名称及规格型号',
      ellipsis: true,
      editable: true,
    },
    {
      title: '数量及单位',
      dataIndex: '数量及单位',
      key: '数量及单位',
      width: 120,
      editable: true,
    },
    {
      title: '单价/总价/币制',
      dataIndex: '单价/总价/币制',
      key: '单价/总价/币制',
      width: 120,
      editable: true,
    },
    {
      title: '原产国',
      dataIndex: '原产国',
      key: '原产国',
      width: 100,
      editable: true,
    },
    {
      title: '最终目的国',
      dataIndex: '最终目的国',
      key: '最终目的国',
      width: 100,
      editable: true,
    },
    {
      title: '境内目的地',
      dataIndex: '境内目的地',
      key: '境内目的地',
      width: 150,
      editable: true,
    },
    {
      title: '征免',
      dataIndex: '征免',
      key: '征免',
      width: 100,
      editable: true,
    },
  ];

  // 渲染商品明细
  const renderProductItems = () => {
    const products = localData.项目 || [];
    const success = isFieldSuccess('项目');
    const rawContent = rawContents?.['项目'];  // 获取商品明细的智能体原始内容

    return (
      <Card 
        title={
          <Space>
            商品明细
            {success ? (
              <Tag icon={<CheckCircleOutlined />} color="success">
                AI提取成功
              </Tag>
            ) : (
              <Tag icon={<CloseCircleOutlined />} color="error">
                AI提取失败
              </Tag>
            )}
            {rawContent && (
              <Tooltip 
                title={<pre style={{ maxHeight: '400px', overflow: 'auto', margin: 0, whiteSpace: 'pre-wrap', fontSize: '12px' }}>{rawContent}</pre>}
                placement="right"
                overlayStyle={{ maxWidth: '600px' }}
              >
                <InfoCircleOutlined style={{ color: '#1890ff', cursor: 'help' }} />
              </Tooltip>
            )}
          </Space>
        }
        size="small" 
        style={{ marginBottom: 16 }}
        className="customs-card"
      >
        <Table
          dataSource={products.map((item, index) => ({ ...item, key: index }))}
          columns={productColumns}
          pagination={false}
          size="small"
          bordered
          scroll={{ x: 1200 }}
        />
      </Card>
    );
  };

  return (
    <div className="result-table-container">
      <Title level={3} style={{ textAlign: 'center', marginBottom: 24 }}>
        中华人民共和国海关进出口货物报关单
      </Title>

      {fieldGroups.map((group) => renderFieldGroup(group))}
      
      {renderProductItems()}
    </div>
  );
};

export default ResultTable;

